package cm.cool.web.util.cookie;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

/**
 * 操作cookie的工具类
 * @author fangzhenx
 * time:2017年10月13日20:37:49
 */
@Component
public class CookieOp {
	
	/**
	 * 添加token信息
	 * @param response
	 * @param cookieName cookie名称
	 * @param cookieValue cookie密码
	 * @return
	 */
	public static boolean setCookie(HttpServletResponse response,String cookieName,String cookieValue){
		
		try {
			Cookie cookie = new Cookie(cookieName,cookieValue);
			cookie.setPath("/");
			response.addCookie(cookie);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	
	/**
	 * 添加带过期时间的token信息
	 * @param response
	 * @param cookieName cookie名称
	 * @param cookieValue cookie密码
	 * @param time 超时时间 (秒)
	 * @return
	 */
	public static boolean setCookieTime(HttpServletResponse response,String cookieName,String cookieValue,int time){
		
		try {
			Cookie cookie = new Cookie(cookieName,cookieValue);
			cookie.setMaxAge(time);
			cookie.setPath("/");
			response.addCookie(cookie);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 拿到token信息
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookie(HttpServletRequest request,String cookieName){
		
		Map<String,Cookie> cookieMap = ReadCookieMap(request);
		    if(cookieMap.containsKey(cookieName)){
		        Cookie cookie = (Cookie)cookieMap.get(cookieName);
		        return cookie.getValue();
		    }else{
		        return null;
		    }   
	}

	
	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
	    Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
	    Cookie[] cookies = request.getCookies();
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie);
	        }
	    }
	    return cookieMap;
	}
}
